package org.lansir.af.reminder;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.lansir.af.R;
import org.lansir.af.dataview.DataViewItemActivity;
import org.lansir.af.ui.CommonFragment.SnoozeAction;
import org.lansir.af.util.Prefs;
import org.lansir.af.util.Utils;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

/**
 * 
 * @author 蓝智宏
 *
 */
public class AlarmReminder {
	private Context servContext = null;
	private Context appContext = null;
	private AudioManager audioManager = null;
	private List<DataViewItemActivity> alarmItems = new ArrayList<DataViewItemActivity>();
	private List<DataViewItemActivity> arrivedAlarmItems = new ArrayList<DataViewItemActivity>();
	private int alarmItemIndex = 0;
	public static final int iNotifyID = 1;
	private NotificationManager mNotificationManager = null;
	private Utils utils;
	private Prefs prefs;

	public AlarmReminder(Context servContext, Context appContext, Utils utils) {
		super();
		this.servContext = servContext;
		this.appContext = appContext;
		this.utils = utils;
		this.prefs = new Prefs(servContext);
		audioManager = (AudioManager) this.servContext
				.getSystemService(Context.AUDIO_SERVICE);
		mNotificationManager = (NotificationManager) this.servContext
				.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	public void removeNotify() {
		mNotificationManager.cancel(iNotifyID);
	}

	public void clear() {
		alarmItems.clear();
	}

	public void addAlarmData(List<DataViewItemActivity> items) {
		this.alarmItems.addAll(items);
	}

	public boolean hasAlarm() {
		return (alarmItems.size() > 0);
	}

	private boolean alarmArrived() {
		boolean flag = false;
		arrivedAlarmItems.clear();
		Calendar currentDate = Calendar.getInstance();
		currentDate.setTimeInMillis(System.currentTimeMillis());
		int iHour = currentDate.get(Calendar.HOUR_OF_DAY);
		int iMinute = currentDate.get(Calendar.MINUTE);
		int iCurrTimeKey = (iHour * 100) + iMinute;
		boolean bSnooze = false;
		
		for (int i = 0; i < alarmItems.size(); i++) {
			DataViewItemActivity alarmDataViewItem = alarmItems.get(i);
			
			/*
			 * 判断是否为Snooze
			 * 1、SnoozeAction == Snooze
			 * 2、当前时间 >= 活动提醒时间
			 * 3、SnoozeCount <= 用户自定义最大次数
			 * 4、(currentDate - alarmDate) % 用户自定义SnoozeTime == 0
			 */
			bSnooze = (alarmDataViewItem.getActionClear() == SnoozeAction.convertToInt(SnoozeAction.Snooze))
								&& (alarmDataViewItem.getSnooze() == 1)
								&& (currentDate.getTimeInMillis() >= alarmDataViewItem.getStartDateAsLong()) 
								&& (alarmDataViewItem.getSnoozeCount() <= prefs.iSnoozeCount) 
								&& (((currentDate.get(Calendar.HOUR_OF_DAY) - alarmDataViewItem.getStartHour()) * 60 + (currentDate.get(Calendar.MINUTE) - alarmDataViewItem.getStartMinute())) % prefs.iSnoozeMinutesOverdue == 0);
//			Log.v("ActivityFairy", "getActionClear:" + (alarmDataViewItem.getActionClear() == SnoozeAction.convertToInt(SnoozeAction.Snooze)));
//			Log.v("ActivityFairy", "Snooze:" + (alarmDataViewItem.getSnooze() == 1));
//			Log.v("ActivityFairy", "TimeInMillis:" + (currentDate.getTimeInMillis() >= alarmDataViewItem.getStartDateAsLong()));
//			Log.v("ActivityFairy", "SnoozeCount:" + (alarmDataViewItem.getSnoozeCount() <= prefs.iSnoozeCount));
//			Log.v("ActivityFairy", "SnoozeCount:" + alarmDataViewItem.getSnoozeCount());
//			Log.v("ActivityFairy", "SnoozeCount:" + prefs.iSnoozeCount);
//			Log.v("ActivityFairy", "Day:" + (((currentDate.get(Calendar.HOUR_OF_DAY) - alarmDataViewItem.getStartHour()) * 60 + (currentDate.get(Calendar.MINUTE) - alarmDataViewItem.getStartMinute())) % prefs.iSnoozeMinutesOverdue == 0));
//			Log.v("ActivityFairy", "iSnoozeOverdue:" + prefs.iSnoozeMinutesOverdue);
			if (alarmDataViewItem.getTimeKey() == iCurrTimeKey || bSnooze) {
				flag = true;
				arrivedAlarmItems.add(alarmItems.get(i));
			}

		}
		return flag;
	}
	
	public Intent getAlarmReceivedDialogIntent(DataViewItemActivity dataViewItemActivity) {
		Intent intentAlarmDialog = new Intent(
				"android.intent.action.ActivityFairy.ACTION_MODE_VIEW_ALARMRECEIVEDDIALOG");
		Bundle bundle = new Bundle();

		//bundle.putString("SUBJECT", alarmItems.get(alarmItemIndex).sSubject);
		bundle.putLong("ROWID", dataViewItemActivity.getId());
		
		intentAlarmDialog.putExtras(bundle);
		intentAlarmDialog.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
		return intentAlarmDialog;
	}

	public void showNotification() {
		if (hasAlarm()) {

			if (alarmArrived()) {
				int iCountActs = arrivedAlarmItems.size();
//				Log.v("ActivityFairy", "AlarmReminder:ArrivedAlarmCount:"
//						+ iCountActs);
				for (alarmItemIndex = 0; alarmItemIndex < arrivedAlarmItems
						.size(); alarmItemIndex++) {
					audioManager.setRingerMode(alarmItems.get(alarmItemIndex)
							.getRingerMode());
					String msgBody = String.format(utils
							.getResStr(R.string.alarmDialogChangeRingerMode),
							this.servContext.getResources().getStringArray(
									R.array.ringerMode)[arrivedAlarmItems.get(
									alarmItemIndex).getRingerMode()]);
					Log.v("ActivityFairy", "msgBody:" + msgBody);
					Toast.makeText(this.servContext, msgBody, 1).show();
					this.appContext.startActivity(getAlarmReceivedDialogIntent(arrivedAlarmItems.get(alarmItemIndex)));
				}
			}
		}
	}
}
